﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SVN.Net.Misc
{

    public static class ErrorProvider
    {
        private const string CST_ERRINFO_KEY = "ErrorInformation";

        #region " Error provider for Controller "

        public static bool HasError(this System.Web.Mvc.Controller ctl)
        {
            return (ctl.TempData[CST_ERRINFO_KEY] != null && ctl.TempData[CST_ERRINFO_KEY].GetType() == typeof(List<string>));
        }

        public static void SetErrorValue(this System.Web.Mvc.Controller ctl,string message)
        {
            // Create the error message data into ViewData.
            if (!HasError(ctl))
                ctl.TempData[CST_ERRINFO_KEY] = new List<string>();
            List<string> el = ctl.TempData[CST_ERRINFO_KEY] as List<string>;
            // Add the message into this list.
            if (!el.Contains(message))
                el.Add(message);
        }

        public static string[] GetErrorValue(this System.Web.Mvc.Controller ctl)
        {
            if (HasError(ctl))
                return (ctl.TempData[CST_ERRINFO_KEY] as List<string>).ToArray();
            else
                throw new NotSupportedException("There is no error information in this controller.");
        }

        public static void ClearErrorValue(this System.Web.Mvc.Controller ctl)
        {
            if (ctl.TempData[CST_ERRINFO_KEY] != null)
                ctl.TempData.Remove(CST_ERRINFO_KEY);
        }

        #endregion

        #region " Error provider for ViewPage "

        public static bool HasError(this System.Web.Mvc.ViewPage vp)
        {
            return (vp.TempData[CST_ERRINFO_KEY] != null && vp.TempData[CST_ERRINFO_KEY].GetType() == typeof(List<string>));
        }

        public static void SetErrorValue(this System.Web.Mvc.ViewPage vp, string message)
        {
            // Create the error message data into ViewData.
            if (!HasError(vp))
                vp.TempData[CST_ERRINFO_KEY] = new List<string>();
            List<string> el = vp.TempData[CST_ERRINFO_KEY] as List<string>;
            // Add the message into this list.
            if (!el.Contains(message))
                el.Add(message);
        }

        public static string[] GetErrorValue(this System.Web.Mvc.ViewPage vp)
        {
            if (HasError(vp))
                return (vp.TempData[CST_ERRINFO_KEY] as List<string>).ToArray();
            else
                return new string[] { };
        }

        public static void ClearErrorValue(this System.Web.Mvc.ViewPage vp)
        {
            if (vp.TempData[CST_ERRINFO_KEY] != null)
                vp.TempData.Remove(CST_ERRINFO_KEY);
        }

        #endregion

    }
}
